package com.huaqin.obeacons;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.huaqin.obeacons.adapter.MainListViewAdapter;
import com.huaqin.obeacons.adapter.ScrollListView;
import com.huaqin.obeacons.utils.*;

public class MessageListFragment extends Fragment implements
		MyDatabaseUtil.NotifyListener {
	private final String TAG = "MessageListFragment";
	private ListView listview;
	private MainListViewAdapter adapter;

	public interface MessageListener {

		void notifyDialog(Context context, int index);

	}

	private MessageListener messageListener;

	public void setListener(MessageListener listener) {
		messageListener = listener;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		MyDatabaseUtil.getInstance(getActivity()).setNotifyListener(this);
		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_message_list, null);
		listview = (ScrollListView) view.findViewById(R.id.main_listview);
		listview.setOnItemClickListener(new listener());
		TextView mEmptyView = (TextView) view.findViewById(R.id.empty);
		listview.setEmptyView(mEmptyView);
		return view;
	}

	@Override
	public void onStart() {
		adapter = new MainListViewAdapter(getActivity(), this);
		// System.out.println("listview="+listview);
		// System.out.println("adapter="+adapter);
		listview.setAdapter(adapter);

		super.onStart();
	}

	class listener implements OnItemClickListener {

		@Override
		public void onItemClick(AdapterView<?> arg0, View v, int position,
				long id) {

			if (messageListener != null) {
				messageListener.notifyDialog(getActivity(), position);
			}

		}
	}

	@Override
	public void nofityMessageListShow() {
		Log.d(TAG, "nofityMessageListShow");
		// Toast.makeText(getActivity(), "hello", Toast.LENGTH_SHORT).show();
		adapter.updateData();
		adapter.notifyDataSetChanged();
		// adapter.notifyDataSetInvalidated();
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		nofityMessageListShow();
		if (adapter == null || adapter.getCount() == 0) {
			// ((TextView) getListView().getEmptyView()).setText("empty");
		}
	}
}
